package org.kinglone.weixin.controller;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kinglone.weixin.kit.SecurityKit;
import org.kinglone.weixin.servlet.WeixinContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class WeixinBasicController {

	@RequestMapping(value="/msg",method=RequestMethod.GET)
	public void handerGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		String signature = request.getParameter("signature");//微信加密签名
		String timestamp = request.getParameter("timestamp");//时间戳
		String nonce = request.getParameter("nonce");//随机数
		String echostr = request.getParameter("echostr");//随机字符串
		System.out.println("4--->signature:"+signature+"---timestamp:"+timestamp+"---nonce:"+nonce+"---echostr:"+echostr);
		//1)将token、timestamp、nonce三个参数进行字典序排序
		String[] arr = {WeixinContext.getInstance().getToken(),timestamp,nonce};
		Arrays.sort(arr);//排序
		StringBuffer sb = new StringBuffer();
		for(String a:arr) {
			sb.append(a);
		}		
		//2）将三个参数字符串拼接成一个字符串进行sha1加密
		String sha1Msg = SecurityKit.sha1(sb.toString());
		System.out.println("5----->sha1Msg:"+sha1Msg);
		if(signature.equals(sha1Msg)) {
			response.getWriter().println(echostr);
		}	
	}
}
